package cn.itsource.pethome.basic.controller;

import cn.itsource.pethome.basic.util.AjaxResult;
import cn.itsource.pethome.basic.util.FastDfsApiOpr;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * FastDfs 文件存储控制层
 */
@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping//RequestPart(接收前台传过来的复杂数据  ，默认name属性是file)
    public AjaxResult upload(@RequestPart(required = true,value = "file") MultipartFile file) throws IOException {
        try {
            //获取文件原始名
            String filename = file.getOriginalFilename();
            //获取文件后缀需要导入commios-io包）
            String extension = FilenameUtils.getExtension(filename);
            //开始上传，返回存储路径
            String  uploadPath = FastDfsApiOpr.upload(file.getBytes(), extension);
            //将返回的路径传递到前台
            return new AjaxResult().setResult(uploadPath);
        } catch (IOException e) {
            e.printStackTrace();
            //将返回的路径传递到前台
            return new AjaxResult(false, "logo上传失败！" + e.getMessage());
        }
    }

    /**
     * 参数：完整路径 /goup1/xxxxx/yyyy
     * 返回值：成功与否，还要返回地址
     * @RequestParam  将请求参数绑定到你控制器的方法参数上（是springmvc中接收普通参数的注解）
     *
     */
    @DeleteMapping
    public AjaxResult del(@RequestParam(required = true,value = "path") String path){
        try {
            //result: "/group1/M00/00/62/wKgABF8yW56AH2oSAAPqXcjoy1s264.jpg"
            //在出现1的地方进行截取
            String pathTmp = path.substring(1); // goup1/xxxxx/yyyy
            //截取到goup1
            String groupName =  pathTmp.substring(0, pathTmp.indexOf("/")); //goup1
            //截取goup1  后面的内容
            String remotePath = pathTmp.substring(pathTmp.indexOf("/")+1);// /xxxxx/yyyy
            System.out.println(groupName);
            System.out.println(remotePath);
            //删除fastdfs上面的文件
            FastDfsApiOpr.delete(groupName, remotePath);
            //返回结果
            return  new AjaxResult(true,"删除成功!");
        } catch (Exception e) {
            e.printStackTrace();
            //返回结果
            return new AjaxResult(false, "删除失败!" + e.getMessage());
        }
    }
}




